<template>
  <main-container>
    <div class="role-list-page">
      <search-form class="mb20">
        <search-item>
          <router-link :to="{ name: 'roleCreate' }">
            <el-button type="primary" icon="el-icon-plus">添加角色</el-button>
          </router-link>
        </search-item>
        <search-item slot="action">
          <el-button type="text" icon="el-icon-refresh" @click="init">刷新列表</el-button>
        </search-item>
      </search-form>
      <v-table
        ref="table"
        :total="total"
        :current-page="page"
        :handleSizeChange="handleSizeChange"
        :handleCurrentChange="handleCurrentChange"
        :data="tableData"
        :columns="columns"
      >
        <el-table-column label="操作" align="center" width="200px">
          <template v-if="scope.row.id !== 1" slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope)">修改</el-button>
            <el-button type="text" @click="handleDel(scope)">删除</el-button>
          </template>
        </el-table-column>
      </v-table>
    </div>
  </main-container>
</template>

<script>
import table from '@/common/mixins/table'
import { getRoleList, delRole } from '@/api/workbench'

export default {
  name: 'roleList',
  mixins: [table],
  data() {
    return {
      tableData: [],
      columns: [
        {
          label: '角色名',
          prop: 'roleName'
        },
        {
          label: '角色描述',
          prop: 'describes',
          render(h, params) {
            let { describes } = params.row
            return h('div', describes || '无')
          }
        },
        {
          label: '使用人数',
          prop: 'count'
        }
      ]
    }
  },
  created() {
    this.init()
  },
  methods: {
    /**
     * 分页查询角色管理
     */
    async init() {
      let { page, pageSize } = this
      let res = await getRoleList({ pageNum: page, pageSize })
      let { code, data } = res
      if (code === 0) {
        let { pageCount, roleList = [] } = data
        this.total = pageCount
        this.tableData = roleList
      }
    },
    /**
     * 修改
     */
    handleEdit(e) {
      let { id } = e.row
      this.$router.push({ name: 'roleCreate', query: { id } })
    },
    /**
     * 删除
     */
    handleDel(e) {
      let { id, count } = e.row
      if (count > 0) {
        return this.$message.warning('该角色被使用中，不能删除')
      }
      this.$confirm('确定删除该角色？', {
        title: '提示',
        type: 'warning'
      })
        .then(async () => {
          let res = await delRole({ roleId: id })
          let { code, msg: message } = res
          if (code === 0) {
            this.$message.success(message)
            this.init()
          }
        })
        .catch(() => {})
    }
  }
}
</script>
